import 'package:drm/base/page.dart';
import 'package:drm/other_bloc/version_bloc.dart';
import 'package:drm/chart_home_page/chart_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:drm/base/user.dart';
import 'package:drm/util/SpUtils.dart';
import 'zi_page.dart';


import 'package:drm/resource/string_resource.dart';

import 'package:drm/dialog/dialog_util.dart';
import 'package:drm/util/loading_dialog.dart';
import 'package:drm/base/qx_entity.dart';
import 'bloc.dart';

import 'package:drm/gdfk/gdfk_home.dart';

class MainSream extends StatefulWidget {
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends PageState<MainSream>{
  String userName;
  String userId;
  User user;
  RefreshController _refreshController;
  MainBloc _mainBloc = new MainBloc();
  VersionBloc _versionBloc = VersionBloc();

  String version = '';

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _refreshController = RefreshController();
    user = SpUtils.getLocalUser();
    userId = user.userId;
    userName = user.loginName;

    _mainBloc.dispatch(MainGetQxEvent(user));
    _versionBloc.dispatch(VersionEvent());
  }

  @override
  addBlocToBlocList() {
    getBlocs().add(_mainBloc);
    getBlocs().add(_versionBloc);
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _refreshController.dispose();
  }
  void _onRefresh(){
    _mainBloc.dispatch(MainGetQxEvent(user));
  }

  @override
  Widget mainView(BuildContext context) {
    return WillPopScope(
        onWillPop: _doubleExit, // look here!
        child: BlocBuilder(
            bloc: _mainBloc,
            builder: (context, mainState) {
              stateDo(context, mainState);
              return Scaffold(
                appBar: AppBar(
                  title: Text(
                    StringRes.appNasme,
                  ),
                  centerTitle: true,
                ),
                drawer: Drawer(
                  child: iniDrawer(context),
                ),
                body: iniPage(context),
              );
            }));
  }

  Widget iniDrawer(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(0),
      child: ListView(
        padding: EdgeInsets.all(0),
        children: <Widget>[
          UserAccountsDrawerHeader(
            accountName: new Text(
              '$userName',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            accountEmail: Text('${StringRes.appNasme}'),
            currentAccountPicture: CircleAvatar(
              backgroundImage: AssetImage('images/touxiang.png'),
            ),
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage('images/userbackground.png'),
                  fit: BoxFit.cover,
                  colorFilter: ColorFilter.mode(
                      Theme.of(context).primaryColor.withOpacity(0.6),
                      BlendMode.hardLight)),
            ),
          ),
          BlocBuilder(
              bloc: _versionBloc,
              builder: (context, state) {
                if (state is VersionState) {
                  version = state.version;
                }
                return ListTile(
                  title: Text('当前版本:$version'),
                  leading: Icon(
                    Icons.info,
                    color: Theme.of(context).primaryColor,
                  ),
                  trailing: Icon(Icons.chevron_right),
                  onTap: () {
                    _versionBloc.dispatch(VersionEvent());
                  },
                );
              }),
          Divider(),
          ListTile(
            title: Text('退出'),
            leading: Icon(
              Icons.cancel,
              color: Theme.of(context).primaryColor,
            ),
            trailing: Icon(Icons.chevron_right),
            onTap: () {
              closeApp();
            },
          ),
          Divider(),
        ],
      ),
    );
  }

  Widget iniPage(BuildContext context) {
    return BlocBuilder(
        bloc: _mainBloc,
        builder: (context, state) {
          if (state is MainGetQxEventState) {
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
            if (state.result.isSuccess) {
              List<QxEntity> qxLists = state.result.data;
              return iniList(context, qxLists);
            } else {
              showToast(state.result.message);
              return Container();
            }
          } else {
            return new Center(
              child: WidgetCreator.createCommonProgressBar(),
            );
          }


        });
  }

  Widget iniList(BuildContext context, List<QxEntity> qxLists) {
    if (qxLists == null || qxLists.length == 0) {
      return Container();
    } else {
      return
        SmartRefresher(
          enablePullDown: true,
          enablePullUp: true,
          header: ClassicHeader(),
          controller: _refreshController,
          onRefresh: _onRefresh,
          child: ListView.builder(
              itemCount: qxLists.length,
              itemBuilder: (context, index) {
                QxEntity item = qxLists[index];

                if (item.children == null || item.children.length == 0) {
                  return ListTile(
                    title: Text(item.text),
                  );
                } else {

                  return Column(
                    children: <Widget>[
                      ListTile(
                        title: Text(item.text),
                      ),
                      Divider(),
                      GridView.count(
                        crossAxisCount: 4,

                        physics: new NeverScrollableScrollPhysics(),
                        //增加
                        shrinkWrap: true,
                        //增加
                        children: iniItems(context, item),
                      ),
                    ],
                  );
                }
              }),
        );







    }
  }

  List<Widget> iniItems(BuildContext context, QxEntity qx) {
    if (user == null) {
      return [Container()];
    } else {
      List<QxEntity> qxChildrens = qx.children;

      List<Widget> items = [];
      if (qx != null) {
        for (int i = 0; i < qxChildrens.length; i++) {
          print( qxChildrens[i].toString());
          items.add(item(context,
              qxChildrens[i]));
        }
      }

      // 共同拥有
//      items.add(
//          item(context, '区域销售额统计', ChartViewFlag.QYXSETJ)); //区域销售额统计----总部，代理商
//      items.add(item(context, '下级订、换、退货统计',
//          ChartViewFlag.XJDHTHTJ)); //下级订、换、退货统计----总部，代理商
//      items.add(item(context, '下级代理商月订货额统计',
//          ChartViewFlag.XJDLSYDHETJ)); //下级代理商月订货额统计----总部，代理商
//      if (user.dlsId == '0') {
//        //总部；
//        items.add(item(context, '下级代理商订货数量统计',
//            ChartViewFlag.XJDLSDHTJ)); //下级代理商订货数量统计----总部
//        items.add(item(context, '所有代理商销售额统计',
//            ChartViewFlag.SYDLSXSETJ)); //所有代理商销售额统计----总部
//      } else {
//        //代理商
//        items.add(item(context, '代理商销售、退货统计',
//            ChartViewFlag.DLS_XS_TH_TJ)); //代理商销售、退货统计----代理商
//        items
//            .add(item(context, '代理商销售额统计', ChartViewFlag.DLS_XSE_TJ)); //----代理商
//      }
      return items;
    }
  }

//  List<Widget> iniItems123(BuildContext context, QxEntity qx) {
//    if (user == null) {
//      return [Container()];
//    } else {
//      List<Widget> items = [];
//      // 共同拥有
//      items.add(
//          item(context, '区域销售额统计', ChartViewFlag.QYXSETJ,)); //区域销售额统计----总部，代理商
//      items.add(item(context, '下级订、换、退货统计',
//          ChartViewFlag.XJDHTHTJ)); //下级订、换、退货统计----总部，代理商
//      items.add(item(context, '下级代理商月订货额统计',
//          ChartViewFlag.XJDLSYDHETJ)); //下级代理商月订货额统计----总部，代理商
//      if (user.dlsId == '0') {
//        //总部；
//        items.add(item(context, '下级代理商订货数量统计',
//            ChartViewFlag.XJDLSDHTJ)); //下级代理商订货数量统计----总部
//        items.add(item(context, '所有代理商销售额统计',
//            ChartViewFlag.SYDLSXSETJ)); //所有代理商销售额统计----总部
//      } else {
//        //代理商
//        items.add(item(context, '代理商销售、退货统计',
//            ChartViewFlag.DLS_XS_TH_TJ)); //代理商销售、退货统计----代理商
//        items
//            .add(item(context, '代理商销售额统计', ChartViewFlag.DLS_XSE_TJ)); //----代理商
//      }
//      return items;
//    }
//  }

  Widget item(
      BuildContext context,  QxEntity qx) {
    return FlatButton(
      onPressed: () {
        itemOnClick(context, qx);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          CachedNetworkImage(
            imageUrl:SpUtils.getBaseUrl()+qx.iconURL.replaceAll('../', ''),
            placeholder: (context, url) => new CircularProgressIndicator(),
            errorWidget: (context, url, error) => new Icon(Icons.error),
          ),

          SizedBox(
            height: 3,
          ),
          Text(
            qx.text,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(fontSize: ScreenUtil.getInstance().setSp(30)),
          ),
        ],
      ),
    );
  }

  //禁止返回键；
  Future<bool> _doubleExit() async {
    return Future.value(false);
  }

  //关闭app；
  void closeApp() async {
    bool result = await DialogUtil.showAlertDailog(context, '确定退出吗？');
    if (result) {
      await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
    }
  }

  void itemOnClick(BuildContext context, QxEntity qx) {
    Widget page;
    var flag ;

    switch(qx.id) {
      case 123://区域销售额统计
        flag = ChartViewFlag.QYXSETJ;
        break;
      case 134://下级订、换、退货统计
        flag = ChartViewFlag.XJDHTHTJ;
        break;
      case 138://所有代理商销售额统计
        flag = ChartViewFlag.SYDLSXSETJ;
        break;
      case 139://下级代理商订货数量统计
        flag = ChartViewFlag.XJDLSDHTJ;
        break;
      case 133://代理商销售退货统计
        flag = ChartViewFlag.DLS_XS_TH_TJ;
        break;
      case 137://下级代理商月订货额统计
        flag = ChartViewFlag.XJDLSYDHETJ;
        break;
      case 136://代理商销售额统计
        flag = ChartViewFlag.DLS_XSE_TJ;
        break;

      case 57://工单反馈；
        flag = GdfkFlag.GDFK;
        break;


    }

    if (flag != null) {

      if(flag is ChartViewFlag) {
        page = ChartPage(
            title: qx.text,
            flag:flag
        );
      }else if ( flag is GdfkFlag){
        page = GdfkHomePage();
      }

      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        return page;
      }));
    }else {
      showToast('暂未开发');
    }
  }

  stateDo(BuildContext context, MainState state) {}
}
